<template>
  <el-scrollbar>
  <div class="common-layout">
    <el-container>
      <!-- 头部 -->
      <el-header>
        <h1>{{ title }}</h1>
      </el-header>
      <!-- 聊天展示区域 -->
      <el-main class="chat-container">
        <div v-for="(message, index) in messages" :key="index" :class="['chat-message', message.type]">
          <!-- 头像和名称 -->
          <div class="avatar">
            <img
              v-if="message.type === 'user'"
              :src="require('@/assets/我.jpg')"
              alt="User Avatar"
            />
            <img
              v-else
              :src="require('@/assets/智能小梦.jpg')"
              alt="Bot Avatar"
            />
          </div>
          <div class="message-wrapper">
            <!-- 名称 -->
            <div class="name">
              {{ message.type === 'user' ? '我' : '智能小梦' }}
            </div>
            <!-- 消息内容 -->
            <div class="message-content" v-html="formatMessageContent(message.content)"></div>
          </div>
        </div>
      
      </el-main>
      <!-- 问答输入区域 -->
      <el-footer>
        <el-input
          v-model="inputMessage"
          placeholder="请输入你的问题"
          @keyup.enter="sendMessage"
          clearable
        >
          <template #append>
            <el-button type="primary" @click="sendMessage">发送</el-button>
          </template>
        </el-input>
      </el-footer>
    </el-container>
  </div>
</el-scrollbar>
</template>
<script>
import { ref, onMounted } from 'vue';
import axios from 'axios';

export default {
  name: 'App',
  setup() {
    const inputMessage = ref(''); // 输入的消息
    const messages = ref([]); // 聊天记录
    const title = ref(''); // 标题
    // 获取标题
    const fetchTitle = async () => {
      try {
        const response = await axios.get('http://localhost:5000/api/title');
        title.value = response.data.title;
      } catch (err) {
        console.error('获取标题失败：', err);
        title.value = '知识图谱问答系统';
      }
    };
    // 获取欢迎消息
    const fetchWelcomeMessage = async () => {
      try {
        const response = await axios.get('http://localhost:5000/api/welcome');
        messages.value.push({
          type: 'bot',
          content: response.data.message,
        });
      } catch (err) {
        console.error('获取欢迎消息失败：', err);
        messages.value.push({
          type: 'bot',
          content: '欢迎使用知识图谱问答系统！',
        });
      }
    };
    // 发送消息
    const sendMessage = async () => {
      if (!inputMessage.value.trim()) {
        return; // 如果输入为空，直接返回
      }
      // 将用户输入添加到聊天记录
      messages.value.push({
        type: 'user',
        content: inputMessage.value,
      });
      // 后端请求
      try {
        const response = await axios.get('http://localhost:5000/api/query', {
          params: { q: inputMessage.value },
        });

        // 将后端返回的结果添加到聊天记录
        messages.value.push({
          type: 'bot',
          content: response.data.result,
        });
      } catch (err) {
        console.error('请求失败：', err);
        messages.value.push({
          type: 'bot',
          content: '抱歉，请求失败，请稍后重试！',
        });
      }

      // 清空输入框
      inputMessage.value = '';
    };

    // 格式化消息内容，将 \n 替换为 <br>
    const formatMessageContent = (content) => {
      return content.replace(/\n/g, '<br>');
    };

    // 在组件挂载时获取标题和欢迎消息
    onMounted(() => {
      fetchTitle();
      fetchWelcomeMessage();
    });

    return {
      inputMessage,
      messages,
      title,
      sendMessage,
      formatMessageContent,
    };
  },
};
</script>

<style>
/* 全局样式，去除页面与窗口的缝隙 */
body, html, #app {
  margin: 0;
  padding: 0;
  height: 100%;
}

.common-layout {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.el-header {
  background-color: #42b983;
  color: white;
  padding: 20px;
  text-align: center;
}

.chat-container {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background-color: #f5f5f5;
}

.chat-message {
  margin-bottom: 15px;
  display: flex;
  align-items: flex-start;
}

.chat-message.user {
  flex-direction: row-reverse; /* 用户消息头像在右侧 */
}

.chat-message.bot {
  flex-direction: row; /* 系统消息头像在左侧 */
}

.avatar {
  width: 40px;
  height: 40px;
}

.avatar img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
}

.message-wrapper {
  max-width: 70%;
}

.name {
  font-size: 12px;
  color: #666;
  margin-bottom: 5px;
}

.user .message-wrapper {
  margin-right: 10px;
}

.bot .message-wrapper {
  margin-left: 10px;
}

.message-content {
  padding: 10px 15px;
  border-radius: 10px;
}

.user .message-content {
  background-color: #42b983;
  color: white;
}

.bot .message-content {
  background-color: #ffffff;
  border: 1px solid #ddd;
  color: #333;
}

.el-footer {
  padding: 20px;
  background-color: #ffffff;
  border-top: 1px solid #ddd;
}

.el-input {
  width: 100%;
}
</style>